<template>
  <div class="login-container">
    <el-card class="login-card">
      <div slot="header" class="login-header">
        <h2>物联网平台登录</h2>
      </div>
      <el-form
          ref="loginForm"
          :model="loginForm"
          :rules="rules"
          class="login-form"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              prefix-icon="User"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              prefix-icon="Lock"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>
        <div class="login-links">
          <router-link to="/sendEmailCode">忘记密码?</router-link>
          <span>|</span>
          <router-link to="/registerUser">注册账号</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleLogin() {
      this.$refs.loginForm.validate(async (valid) => {
        if (valid) {
          try {
            console.log('准备发送请求：', this.loginForm); // 打印请求参数
            const response = await this.$axios.post('/login', null, {
              params: {
                username: this.loginForm.username,
                password: this.loginForm.password
              }
            })
            console.log('后端响应：', response.data); // 打印后端返回数据

            if (response.data.code === 200) {
              localStorage.setItem('userInfo', JSON.stringify(response.data.data))
              this.$message.success('登录成功')
              this.$router.push('/home')
            } else {
              this.$message.error(response.data.msg)
            }
          } catch (error) {
            // 详细打印错误信息
            console.error('请求失败详情：', error);
            if (error.response) {
              // 后端有响应但状态码错误（如404、500）
              console.error('响应状态码：', error.response.status);
              console.error('响应数据：', error.response.data);
              this.$message.error(`服务器错误：${error.response.status}`);
            } else if (error.request) {
              // 后端无响应（如接口地址错误、端口错误）
              this.$message.error('网络错误：无法连接到服务器，请检查后端是否启动');
            } else {
              // 其他错误
              this.$message.error('请求失败：' + error.message);
            }
          }
        }
      })
    }
  }
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 400px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
}

.login-form {
  padding: 20px;
}

.login-btn {
  width: 100%;
}

.login-links {
  text-align: center;
  margin-top: 15px;
}

.login-links a {
  color: #409eff;
  margin: 0 10px;
  text-decoration: none;
}

.login-links span {
  color: #ccc;
}
</style>